package com.xxx.video.commen.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class AppSignUtils {
    private static AppSignUtils instance;

    private AppSignUtils() {

    }

    public static AppSignUtils getInstance() {
        if (instance == null) {
            synchronized (AppSignUtils.class) {
                if (instance == null) {
                    instance = new AppSignUtils();
                }
            }
        }
        return instance;
    }

    /**
     *
     */
    public List<Integer> getSignInfo() {
        List<Integer> signInfoList = new ArrayList<>();
        signInfoList.add(73);
        signInfoList.add(156);
        signInfoList.add(86);
        signInfoList.add(93);
        signInfoList.add(40);
        signInfoList.add(5);
        signInfoList.add(215);
        signInfoList.add(8);
        signInfoList.add(115);
        signInfoList.add(200);
        signInfoList.add(12);
        signInfoList.add(131);
        signInfoList.add(122);
        signInfoList.add(244);
        signInfoList.add(71);
        signInfoList.add(129);
        return signInfoList;
    }

    /**
     * @param context 上下文
     */
    @SuppressLint("PackageManagerGetSignatures")
    public List<Integer> getAppSign(Context context) {
        PackageManager pm = context.getPackageManager();
        String name = context.getPackageName();
        List<Integer> signInfoList = new ArrayList<>();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(name, PackageManager.GET_SIGNATURES);
            String sign = packageInfo.signatures[0].toCharsString();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] md5sum = md5.digest(sign.getBytes());
            for (byte b : md5sum) {
                if (b < 0) {
                    signInfoList.add(256 + b);
                    Log.i("签名", 256 + b + "");
                    continue;
                }
                signInfoList.add(Integer.parseInt("" + b));
                Log.i("签名", "" + b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return signInfoList;
    }

    public boolean isRight(Context context) {
        List<Integer> localSign = getAppSign(context);
        List<Integer> signInfoList = getSignInfo();
        if (ListUtils.isEmpty(localSign) || ListUtils.isEmpty(signInfoList)) {
            return false;
        }
        if (localSign.size() != signInfoList.size()) {
            return false;
        }
        for (int i = 0; i < localSign.size(); i++) {
            if (!localSign.get(i).equals(signInfoList.get(i))) {
                return false;
            }
        }
        return true;
    }
}
